module game
{
	export class EditorMap extends egret.DisplayObjectContainer
	{
		private original_map:Array<number>;
		private original_row:number;
		private original_col:number;
		private _map:Array<number>;
		private _row:number;
		private _col:number;

		private _gritSp:egret.Sprite;
		private _touchRect:eui.Rect;
		private _gridArr:Array<Array<BaseGrid>>;

		public constructor()
		{
			super();
		}

		/**
		 * 地图初始化需要的参数
		 * @param map
		 * @param row
		 * @param col
		 */
		public init(map:Array<number>,row:number,col:number):void
		{
			this._gritSp = new egret.Sprite();
			this.addChild(this._gritSp);

			this.map = map;
			this.row = row;
			this.col = col;

			this._gridArr = new Array<Array<BaseGrid>>();
			this._touchRect = new eui.Rect();
			this._touchRect.addEventListener(egret.TouchEvent.TOUCH_TAP,this.onTouch,this);

			this.build();
		}

		private _startX:number;
		private _startY:number;
		private _curGrid:BaseGrid;

		private onTouch(e:egret.TouchEvent):void
		{
			// console.warn("onTouch....",e.type);
			switch(e.type)
			{
				case egret.TouchEvent.TOUCH_TAP:
					if(this._curGrid){this._curGrid.select(false);}
					//记录起始位置
					this._startX = e.localX;
					this._startY = e.localY;
					this.checkStart();
					break;
			}
		}

		/**检测起始点 */
		private checkStart():void
		{
			let posX = Math.floor(this._startX/40);
			let posY = Math.floor(this._startY/40);

			// console.log(posX,posY);

			let grid = this._gridArr[posX][posY];
			if(grid)
			{
				this._curGrid = grid;
				grid.isBlank = !grid.isBlank;

				this._map[posX + posY*this._col] = grid.isBlank?0:1;
				console.warn(this._map);
			}
		}

		/**地图数据 */
		public set map(value:Array<number>)
		{
			this.original_map = value;
			this._map = value;
		}

		public get map():Array<number>
		{
			return this._map;
		}

		public set row(value:number)
		{
			this.original_row = value;
			this._row = value;
		}

		public set col(value:number)
		{
			this.original_col = value;
			this._col = value;
		}

		public get row():number
		{
			return this._row;
		}

		public get col():number
		{
			return this._col;
		}

		/**构建地图 */
		private build():void
		{
			let arr = this._map;
			for(let i = 0;i < this._col;i++)
			{
				this._gridArr[i] = new Array<BaseGrid>();

				for(let j = 0;j < this._row;j++)
				{
					let type = this._map[i + j*this._col];
					let grid = new BaseGrid();
					grid.type = type;
					grid.isBlank = type == 0;
					this._gritSp.addChild(grid);
					grid.init();
					grid.x = i*40;
					grid.y = j*40;

					this._gridArr[i][j] = grid;
				}
			}
			
			this._touchRect.width = 40*this._col;
			this._touchRect.height = 40*this._row;
			this._touchRect.fillColor = 0;
			this._touchRect.alpha = 0.01;
			this.addChild(this._touchRect);
		}
	}
}